/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.http.websocketx.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * A HTTP server which serves Web Socket requests at:
 * <p/>
 * http://localhost:8080/websocket
 * <p/>
 * Open your browser at <a href="http://localhost:8080/">http://localhost:8080/</a>, then the demo page will be loaded
 * and a Web Socket connection will be made automatically.
 * <p/>
 * This server illustrates support for the different web socket specification versions and will work with:
 * <p/>
 * <ul>
 * <li>Safari 5+ (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 6-13 (draft-ietf-hybi-thewebsocketprotocol-00)
 * <li>Chrome 14+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Chrome 16+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * <li>Firefox 7+ (draft-ietf-hybi-thewebsocketprotocol-10)
 * <li>Firefox 11+ (RFC 6455 aka draft-ietf-hybi-thewebsocketprotocol-17)
 * </ul>
 */
public final class WebSocketServer {
    private static Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "9443" : "9090"));
    static final List<Integer> ports = new ArrayList<Integer>(){{
        add(9090);
        add(9091);
        add(9092);
        add(9093);
        add(9094);
    }};


    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }
        EventLoopGroup bossGroup = new NioEventLoopGroup(5);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG,1024)//等待队列大小
//                    .option(ChannelOption.SO_KEEPALIVE,true)//保持连接活性 2小时无动态的时候会触发此机制
//                    .option(ChannelOption.TCP_NODELAY,true)//无延迟发送消息
//                    .option(ChannelOption.SO_LINGER,100)//阻塞100ms close()调用时间
                    .childHandler(new WebSocketServerInitializer(sslCtx));


            /*多个端口，同一个handler(需要不同的HANDLER时需要绑定不同的ServerBootStrap)*/
//           for(Integer p:ports){
               Channel ch = b.bind(PORT).sync().channel();
               Channel ch1 = b.bind(PORT+1).sync().channel();
               Channel ch2 = b.bind(PORT+2).sync().channel();
               Channel ch3 = b.bind(PORT+3).sync().channel();
               Channel ch4 = b.bind(PORT+4).sync().channel();

               logger.info("server start at time:"+new Date()+",listener port:"+ports.toString());

               ch.closeFuture().sync();//此方法会阻塞以下所有方法
//               ch1.closeFuture().sync();
//               ch2.closeFuture().sync();
//               ch3.closeFuture().sync();
//               ch4.closeFuture().sync();
//           }
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
